'use strict';
const db = uniCloud.database();  // 确保数据库对象正确初始化
const $ = db.command;  // 数据库命令

/**
 * 云函数：获取用户答题记录
 * @param {Object} event - 请求参数
 * @param {string} event.user_id - 用户ID
 * @param {string} [event.date] - 筛选日期（格式：YYYY-MM-DD）
 * @param {number} [event.skip] - 分页偏移量
 * @param {number} [event.limit] - 每页记录数
 * @returns {Object} - 返回答题记录
 */
exports.main = async (event, context) => {
  const { user_id, date, skip = 0, limit = 20 } = event;

  try {
    if (!user_id) {
      return { code: -1, msg: '缺少用户ID' };
    }

    // 获取答题记录集合
    const answerHistoryCollection = db.collection('answer_history');
    const questionsCollection = db.collection('questions'); // 假题目存储在 questions 集合

    // 构造查询条件
    const query = { user_id };
    if (date) {
      const selectedDate = new Date(date);
      const startOfDay = new Date(selectedDate.setHours(0, 0, 0, 0));
      const endOfDay = new Date(selectedDate.setHours(23, 59, 59, 999));
      query.answered_at = $.gte(startOfDay).lte(endOfDay);
    }

    // 查询总记录数（不受 limit 限制）
    const totalRes = await answerHistoryCollection.where(query).count();
    const totalQuestions = totalRes.total || 0;

    if (totalQuestions === 0) {
      return { code: -1, msg: '没有找到答题记录' };
    }

    // 查询分页记录
    const res = await answerHistoryCollection.where(query)
      .skip(skip)
      .limit(limit)
      .orderBy('answered_at', 'desc')
      .get();

    const answerHistory = res.data || [];

    // 获取题目详情（通过 question_id 关联）
    const questionIds = answerHistory.map(record => record.question_id);
    const questionsRes = await questionsCollection.where({
      _id: $.in(questionIds)
    }).get();
    const questionsMap = {};
    questionsRes.data.forEach(q => {
      questionsMap[q._id] = {
        content: q.content,
        options: q.options,
        correct_answer: q.answer
      };
    });

    // 格式化答题记录，合并题目详情
    const formattedHistory = answerHistory.map(record => ({
      _id: record._id,
      question_id: record.question_id,
      content: questionsMap[record.question_id]?.content || '题目内容缺失',
      options: questionsMap[record.question_id]?.options || {},
      correct_answer: questionsMap[record.question_id]?.correct_answer || '',
      user_answer: record.answer || '',
      explanation: record.explanation || '暂无解析',
      answered_at: record.answered_at,
      correct: record.correct !== undefined ? record.correct : false
    }));

    // 计算正确答题数（基于查询到的记录）
    let correctCount = formattedHistory.filter(record => record.correct).length;

    // 如果查询到的记录数少于总数，单独查询正确记录总数
    if (formattedHistory.length < totalQuestions) {
      const correctRes = await answerHistoryCollection.where({
        ...query,
        correct: true
      }).count();
      correctCount = correctRes.total || 0;
    }

    // 计算正确率
    const correctRate = totalQuestions > 0 ? (correctCount / totalQuestions) * 100 : 0;

    return {
      code: 0,
      data: {
        totalQuestions,
        correctCount,
        correctRate: correctRate.toFixed(2),
        answer_history: formattedHistory
      },
      msg: '成功获取答题记录'
    };
  } catch (e) {
    console.error('获取答题记录失败:', e);
    return { code: -1, msg: '获取答题记录失败' };
  }
};